package com.ccccat.www.msgs;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.ccccat.www.msgs.bean.DataBean;
import com.ccccat.www.msgs.bean.TempBean;
import com.ccccat.www.msgs.bean.WorkerTime;
import com.ccccat.www.msgs.util.DateUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.neovisionaries.ws.client.*;

import java.util.*;

import static com.ccccat.www.msgs.Receiver.AlarmRecevier.ws;
import static com.ccccat.www.msgs.Receiver.AlarmRecevier.wsListener;

/**
 * 继承默认的监听空实现WebSocketAdapter,重写我们需要的方法
 * onTextMessage 收到文字信息
 * onConnected 连接成功
 * onConnectError 连接失败
 * onDisconnected 连接关闭
 */
public class WsListener extends WebSocketAdapter {

    private Context context;
    myTimerTask timerTask;

    public WsListener(Context context) {
        this.context = context;
    }

    @Override
    public void onTextMessage(WebSocket websocket, String text) throws Exception {
        super.onTextMessage(websocket, text);
        JsonObject asJsonObject = new JsonParser().parse(text).getAsJsonObject();
        String type = asJsonObject.get("type").getAsString();
        switch (type) {
            case "setPhone":
                JsonArray asJsonArray = asJsonObject.get("data").getAsJsonObject().get("phones").getAsJsonArray();
                //保存当前数据到库里；
                if (asJsonArray != null || asJsonArray.size() > 0) {
                    //检查有没有数据，有数据，读取出来，

                    SharedPreferences sharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE);
                    String TempBeanStr = sharedPreferences.getString("TempBean", null);

                    String currentDate = DateUtil.getCurrentDate("yyyy-MM-dd");
                    //不为空转对象，判断是不是今天的数据
                    if (TempBeanStr != null) {

                        TempBean tempBean = new Gson().fromJson(TempBeanStr, TempBean.class);
                        if (tempBean.getName().equals(currentDate)) {
                            //累加
                            tempBean.setNum(tempBean.getNum() + asJsonArray.size());
                            String s = new Gson().toJson(tempBean);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("TempBean", s);
                            editor.commit();
                            Log.e("二次存储", "" + s);
                        } else {
                            //全新存储

                            String s = new Gson().toJson(new TempBean(currentDate, asJsonArray.size()));
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("TempBean", s);
                            editor.commit();
                            Log.e("全新存储", "" + s);
                        }
                    } else {
                        //全新存储
                        String s = new Gson().toJson(new TempBean(currentDate, asJsonArray.size()));
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString("TempBean", s);
                        editor.commit();
                        Log.e("全新存储", "" + s);
                    }
                }


                for (JsonElement jsonElement : asJsonArray) {
                    if (jsonElement != null && jsonElement.getAsString().length() > 0) {
                        ConstData.phones.push(jsonElement.getAsString());
                    }
                }
                JsonArray messages = asJsonObject.get("data").getAsJsonObject().get("messages").getAsJsonArray();
                for (JsonElement jsonElement : messages) {
                    if (jsonElement != null && jsonElement.getAsString().length() > 0) {
                        ConstData.contest.push(jsonElement.getAsString());
                    }
                }
                break;

            case "data":
                String string = asJsonObject.get("data").toString();
                WorkerTime workerTime = new Gson().fromJson(string, WorkerTime.class);
                ConstData.workerTimeHash = workerTime;
                break;
        }

    }

    @Override
    public void onConnected(WebSocket websocket, Map<String, List<String>> headers)
            throws Exception {
        super.onConnected(websocket, headers);
        ConstData.AUTH_DATA.setState("上线了");
        ConstData.AUTH_DATA.setTime(System.currentTimeMillis() / 1000 + "");
        String report = new Gson().toJson(new DataBean("report", ConstData.AUTH_DATA.getName(), ConstData.AUTH_DATA));
        Log.i("----------", "连接成功");
        ConstData.AUTH_DATA.setState("心跳中");
        websocket.sendText(report);
        timerTask = new myTimerTask(websocket);
        Timer timer = new Timer(true);
        timer.schedule(timerTask, 0, 10000);//定时每秒执行一次

    }

    @Override
    public void onConnectError(WebSocket websocket, WebSocketException exception)
            throws Exception {
        super.onConnectError(websocket, exception);
        Log.i("----------", "：" + exception.getMessage());
        try {
            wsListener=null;
            ws=null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer)
            throws Exception {
        super.onDisconnected(websocket, serverCloseFrame, clientCloseFrame, closedByServer);
        Log.i("----------", "断开连AuthData接");
        timerTask.cancel();
        try {
            wsListener=null;
            ws=null;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //定时任务,定时发送message
    private class myTimerTask extends TimerTask {

        private WebSocket webSocket;

        myTimerTask(WebSocket webSocket) {
            this.webSocket = webSocket;
        }

        @Override
        public void run() {
            Log.i("----------", ConstData.AUTH_DATA.toString());
            ConstData.AUTH_DATA.setTime(System.currentTimeMillis() / 1000 + "");
            String report = new Gson().toJson(new DataBean("report", ConstData.AUTH_DATA.getName(), ConstData.AUTH_DATA));
            webSocket.sendText(report);
            if (ConstData.phones.size() == 0) {

                int temp = 0;
                try {

                    SharedPreferences sharedPreferences = context.getSharedPreferences("data", Context.MODE_PRIVATE);
                    String TempBeanStr = sharedPreferences.getString("TempBean", null);
                    if (TempBeanStr != null) {
                        String currentDate = DateUtil.getCurrentDate("yyyy-MM-dd");
                        TempBean tempBean = new Gson().fromJson(TempBeanStr, TempBean.class);
                        if (tempBean.getName().equals(currentDate)) {

                            if (tempBean.getNum() != null) {
                                temp = tempBean.getNum();
                                ConstData.AUTH_DATA.setReadTotal(temp);
                            }

                        }

                    }
                    Log.e("全新读取", "" +TempBeanStr);

                    String getPhone = new Gson().toJson(new DataBean("getPhone", ConstData.AUTH_DATA.getName(), temp));
                    Log.e("全新读取------------", "" +getPhone);

                    webSocket.sendText(getPhone);
                } catch (Exception e) {

                }

            }
        }
    }
}
